<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <title>Custom Select</title>
  <style>
    .custom-select {
      position: relative;
      width: 240px;
      font-family: sans-serif;
    }
    .custom-select input {
      width: 100%;
      box-sizing: border-box;
      padding: 8px;
    }
    .dropdown {
      position: absolute;
      top: 100%;
      left: 0;
      right: 0;
      border: 1px solid #ccc;
      background: #fff;
      max-height: 200px;
      overflow-y: auto;
      display: none;
      z-index: 10;
    }
    .dropdown.visible {
      display: block;
    }
    .dropdown div {
      padding: 8px;
      cursor: pointer;
    }
    .dropdown div:hover {
      background-color: #f0f0f0;
    }
    .clear-btn {
      position: absolute;
      right: 8px;
      top: 8px;
      cursor: pointer;
      color: #999;
    }
  </style>
</head>
<body>

<div class="custom-select">
  <input type="text" id="selectInput" placeholder="Select" autocomplete="off" />
  <span class="clear-btn" id="clearBtn" style="display: none;">×</span>
  <div class="dropdown" id="dropdown"></div>
</div>

<script>
  const options = [
    { label: "Option A", value: "a" },
    { label: "Option B", value: "b" },
    { label: "Option C", value: "c" },
    { label: "Another", value: "x" }
  ];

  const input = document.getElementById("selectInput");
  const dropdown = document.getElementById("dropdown");
  const clearBtn = document.getElementById("clearBtn");

  let selectedValue = null;

  function renderOptions(filter = "") {
    dropdown.innerHTML = "";
    const filtered = options.filter(o =>
      o.label.toLowerCase().includes(filter.toLowerCase())
    );
    filtered.forEach(option => {
      const div = document.createElement("div");
      div.textContent = option.label;
      div.addEventListener("click", () => {
        input.value = option.label;
        selectedValue = option.value;
        dropdown.classList.remove("visible");
        clearBtn.style.display = "block";
      });
      dropdown.appendChild(div);
    });
    dropdown.classList.toggle("visible", filtered.length > 0);
  }

  input.addEventListener("focus", () => {
    renderOptions(input.value);
  });

  input.addEventListener("input", () => {
    renderOptions(input.value);
  });

  clearBtn.addEventListener("click", () => {
    input.value = "";
    selectedValue = null;
    clearBtn.style.display = "none";
    renderOptions("");
  });

  document.addEventListener("click", (e) => {
    if (!e.target.closest(".custom-select")) {
      dropdown.classList.remove("visible");
    }
  });
</script>

</body>
</html>
